package com.css.dzj.dzjap.modules.force.service.impl;


import com.css.dzj.dzjap.common.util.Constant;
import com.css.dzj.dzjap.common.util.R;
import com.css.dzj.dzjap.common.util.ServiceUtil;
import com.css.dzj.dzjap.modules.export.entity.ExcelData;
import com.css.dzj.dzjap.modules.export.service.ExportExcelUtils;
import com.css.dzj.dzjap.modules.force.entity.ApJgxxForceEntity;
import com.css.dzj.dzjap.modules.force.entity.QApJgxxForceEntity;
import com.css.dzj.dzjap.modules.force.mapper.ForceMapper;
import com.css.dzj.dzjap.modules.force.service.ForceService;
import com.css.dzj.dzjap.sys.user.entity.LoginUser;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.ComparableExpressionBase;
import com.querydsl.core.types.dsl.NumberExpression;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ForceServiceImpl implements ForceService {

    @Autowired
    private ForceMapper forceMapper;
    @Autowired
    JPAQueryFactory jpaQueryFactory;
    @Autowired
    ServiceUtil serviceUtil;
    @Override
    public ApJgxxForceEntity getForce(String forceId) {
        if(StringUtils.isEmpty(forceId)){
            throw new RuntimeException("参数为空");
        }
        QApJgxxForceEntity qforce = QApJgxxForceEntity.apJgxxForceEntity;

        return jpaQueryFactory
                .selectFrom(qforce)
                .where(  qforce.forceId.eq(forceId),
                        qforce.delFlag.eq(Constant.NO_DELETE)
                )
                .fetchOne();
    }

    @Override
    @Transactional
    public void updateForce(ApJgxxForceEntity apJgxxForceEntity) {

    }

    @Override
    @Transactional
    public Boolean delForce(String forceId) {
        if(StringUtils.isEmpty(forceId)){
            return  false;
        }
        QApJgxxForceEntity qforce = QApJgxxForceEntity.apJgxxForceEntity;
        try{
            jpaQueryFactory
                    .update(qforce)
                    .set(qforce.delFlag,Constant.DELETE)
                    .where(
                            qforce.delFlag.eq(Constant.NO_DELETE),
                            qforce.forceId.eq(forceId)
                    )
                    .execute();
            return true;
        }catch (Exception e){
            return false;
        }
    }


    @Override
    @Transactional
    public String addForce(ApJgxxForceEntity apJgxxForceEntity) {
        /*apJgxxForceEntity.setInsertDate(new Date());*/
        apJgxxForceEntity.setDelFlag(Constant.NO_DELETE);
        apJgxxForceEntity.setCreatTime(new Date());
        forceMapper.save(apJgxxForceEntity);
        return null;
    }

    /**
     * 分页查询
     * @param pageable
     * @return
     */
    @Override
    public QueryResults<ApJgxxForceEntity> getAllForce(Pageable pageable) {

        QApJgxxForceEntity qforce = QApJgxxForceEntity.apJgxxForceEntity;
        Predicate predicate = qforce.isNotNull().or(qforce.isNull());
        predicate = ExpressionUtils.and(predicate, qforce.delFlag.eq(Constant.NO_DELETE));
        return  jpaQueryFactory
                .selectFrom(qforce)
                .where(
                        predicate
                )
                .orderBy(qforce.insertDate.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }

    @Override
    public QueryResults<ApJgxxForceEntity> getAllContation(Pageable pageable, String superviseId, String forceActionName, String forceActionCode, String submittedDate) {
        QApJgxxForceEntity qforce = QApJgxxForceEntity.apJgxxForceEntity;
        Predicate predicate = qforce.isNotNull().or(qforce.isNull());
        predicate = ("".equals(superviseId) || superviseId == null) ? predicate : ExpressionUtils.and(predicate, qforce.superviseId.like("%"+superviseId+"%"));
        predicate = ("".equals(forceActionName) || forceActionName == null) ? predicate : ExpressionUtils.and(predicate, qforce.forceActionName.like("%"+forceActionName+"%"));
        predicate = ("".equals(forceActionCode) || forceActionCode == null) ? predicate : ExpressionUtils.and(predicate, qforce.checkActionCode.like("%"+forceActionCode+"%"));
        predicate = ExpressionUtils.and(predicate, qforce.delFlag.eq(Constant.NO_DELETE)) ;
        if((!StringUtils.isEmpty(submittedDate))){
            //Date startDate = new Date();
            Date submittedTime=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                submittedTime = sf.parse(submittedDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, qforce.submittedDate.between(submittedTime,submittedTime));
        }
        return jpaQueryFactory
                .selectFrom(qforce)
                .where(predicate)
                .orderBy(
                        qforce.insertDate.desc())
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .fetchResults();
    }

    @Override
    public HashMap getCount() {
        QApJgxxForceEntity q=QApJgxxForceEntity.apJgxxForceEntity;
        List<ApJgxxForceEntity> list=jpaQueryFactory.selectFrom(q).where(q.delFlag.eq(Constant.NO_DELETE)).fetch();
        HashMap map=new HashMap();
        for (ApJgxxForceEntity ap:list) {
            String address=ap.getImplementInstitution();
            Long count=jpaQueryFactory.select(q.implementInstitution.count()).from(q).
                    where(q.delFlag.eq(Constant.NO_DELETE),q.implementInstitution.eq(address),q.forceId.eq(ap.getForceId())).fetchOne();
            Long value=(Long)map.get(address);
            if(value==null) {
                if(count!=0) {
                    map.put(address, count);
                }
            }else {
                value=count.longValue()+value.longValue();
                map.put(address,value);
            }
        }
        return map;
    }

    @Override
    public HashMap getCountByYear(String year) {
        QApJgxxForceEntity q=QApJgxxForceEntity.apJgxxForceEntity;
        Predicate predicate=q.isNotNull().or(q.isNull());
        List<ApJgxxForceEntity> list=jpaQueryFactory.selectFrom(q).where(q.delFlag.eq(Constant.NO_DELETE)).fetch();
        HashMap map=new HashMap();
        for (ApJgxxForceEntity ap:list) {
            String address=ap.getImplementInstitution();
            ComparableExpressionBase<?> creatYear = q.creatTime.year();
            predicate =ExpressionUtils.and(predicate,((NumberExpression) creatYear).stringValue().eq(year)) ;
            Long count=jpaQueryFactory.select(q.implementInstitution.count()).from(q).
                    where(q.delFlag.eq(Constant.NO_DELETE),q.implementInstitution.eq(address),q.forceId.eq(ap.getForceId()),predicate).fetchOne();
            Long value=(Long)map.get(address);
            if(value==null) {
                if(count!=0) {
                    map.put(address, count);
                }
            }else {
                value=count.longValue()+value.longValue();
                map.put(address,value);
            }
        }
        return map;
    }

    @Override
    public Long getOpCheck(HttpServletRequest request) {
        QApJgxxForceEntity q=QApJgxxForceEntity.apJgxxForceEntity;
        /**
         * 获取suser
         */
        R r = serviceUtil.getUserInfoByRequest(request);
        String suserName = "";
        String location = "";
        String address="";
        String userUnit ="";
        String orgName="";
        if(r.getCode().equals("200")){
            LoginUser userInfo =  (LoginUser)r.get("data");
            /**
             * 获取用户的省份
             */
            orgName = userInfo.getOrgName();

        }
        Long count=jpaQueryFactory.select(q.implementInstitution.count()).from(q).where(q.implementInstitution.eq(orgName),q.delFlag.eq(Constant.NO_DELETE)).fetchOne();
        return count;
    }

    /**
     * 多条件查询强制行为
     */
    @Override
    public QueryResults<ApJgxxForceEntity> getWtContation(String superviseId, String forceActionName, String implementInstitution, Pageable pageable) {

        QApJgxxForceEntity qforce = QApJgxxForceEntity.apJgxxForceEntity;
        Predicate predicate = qforce.isNotNull().or(qforce.isNull());
        predicate = ("".equals(superviseId) || superviseId == null) ? predicate : ExpressionUtils.and(predicate, qforce.superviseId.like("%"+superviseId+"%"));
        predicate = ("".equals(forceActionName) || forceActionName == null) ? predicate : ExpressionUtils.and(predicate, qforce.forceActionName.like("%"+forceActionName+"%"));
        predicate = ("".equals(implementInstitution) || implementInstitution == null) ? predicate : ExpressionUtils.and(predicate, qforce.implementInstitution.like("%"+implementInstitution+"%"));

        predicate = ExpressionUtils.and(predicate, qforce.delFlag.eq(Constant.NO_DELETE)) ;
        return jpaQueryFactory
                .selectFrom(qforce)
                .where(predicate)
                .orderBy(
                        qforce.insertDate.desc())
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .fetchResults();
    }

    /**
     * 根据参数导出数据到Excel
     */
    @Override
    public List<ApJgxxForceEntity> forceList(String superviseId, String forceActionName, String implementInstitution) {
        QApJgxxForceEntity qforce = QApJgxxForceEntity.apJgxxForceEntity;
        Predicate predicate = qforce.isNotNull().or(qforce.isNull());
        predicate = ("".equals(superviseId) || superviseId == null) ? predicate : ExpressionUtils.and(predicate, qforce.superviseId.like("%"+superviseId+"%"));
        predicate = ("".equals(forceActionName) || forceActionName == null) ? predicate : ExpressionUtils.and(predicate, qforce.forceActionName.like("%"+forceActionName+"%"));
        predicate = ("".equals(implementInstitution) || implementInstitution == null) ? predicate : ExpressionUtils.and(predicate, qforce.implementInstitution.like("%"+implementInstitution+"%"));
        predicate = ExpressionUtils.and(predicate, qforce.delFlag.eq(Constant.NO_DELETE)) ;

        List<ApJgxxForceEntity> forceList =  jpaQueryFactory
                                                    .selectFrom(qforce)
                                                    .where(predicate)
                                                    .orderBy(
                                                            qforce.insertDate.desc())
                                                    .fetch();
                                return forceList;
    }

    /**
     * 多条件导出数据
     */
    @Override
    public void exportForceToExcel(HttpServletResponse response, List<ApJgxxForceEntity> forceList) {

        if (forceList == null || forceList.size() < 0) {
            throw new RuntimeException("强制行为为空");
        }
        // 创建导出实体
        ExcelData data = new ExcelData();
        data.setName("强制行为");
        /**
         * 设置Excel标题
         */
        ArrayList<String> titles = new ArrayList<>();
        titles.add("记录唯一标识");
        titles.add("监管事项目录编码");
        titles.add("强制行为名称");
        titles.add("强制行为编号");
        titles.add("实施机构");
        data.setTitles(titles);
        /**
         * 处理行数据
         */
        ArrayList<List<Object>> rows = new ArrayList<>();
        for (ApJgxxForceEntity forceEntity : forceList) {
            ArrayList<Object> row = new ArrayList<>();
            row.add(forceEntity.getRecordUniqueIdentity());
            row.add(forceEntity.getSuperviseId());
            row.add(forceEntity.getForceActionName());
            row.add(forceEntity.getForceActionCode());
            row.add(forceEntity.getImplementInstitution());
            rows.add(row);
        }
        data.setRows(rows);
        try {
            // 导出
            ExportExcelUtils.exportExcel(response, "强制行为.xlsx", data);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     *根据ids查询导出数据
     */
    @Override
    public List<ApJgxxForceEntity> queryByIds(String ids) {
        if (com.alibaba.druid.util.StringUtils.isEmpty(ids)) {
            throw new RuntimeException("ids为空!");
        }
        List<String> idList = Arrays.asList(ids.split(","));
        List<ApJgxxForceEntity> forceList = forceMapper.findAllById(idList);
        return forceList;
    }

    /**
     * 统计数
     */
    @Override
    public String getForceCount() {
        QApJgxxForceEntity qforce = QApJgxxForceEntity.apJgxxForceEntity;
        Long l = jpaQueryFactory.select(qforce.forceId.count())
                .from(qforce)
                .fetchCount();
        if(l!=null){
            return  l.toString();
        }
        return "0";
    }
}
